package com.weilele.mvvm.view

import android.content.Context
import android.util.AttributeSet
import com.weilele.mvvm.R
import com.weilele.mvvm.base.helper.ignoreError
import com.weilele.mvvm.widget.BaseFrameLayout

/**
 * 根据宽度，按照比例决定高度
 * 或者
 * 根据高度，按照比例决定宽度
 */
open class SmartWidthOrHeightLayout : BaseFrameLayout {
    companion object {
        const val BASE_WIDTH = -1
        const val BASE_HEIGHT = 1
        const val BASE_NULL = 0
    }

    var aspectRatio = 1f
        set(value) {
            field = value
            if (isAttachedToWindow) {
                requestLayout()
            }
        }

    //默认 宽比高
    var aspectRatioStyle = BASE_NULL
        set(value) {
            field = value
            if (isAttachedToWindow) {
                requestLayout()
            }
        }

    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        attrs?.let {
            context.obtainStyledAttributes(attrs, R.styleable.SmartWidthOrHeightLayout).apply {
                getString(R.styleable.SmartWidthOrHeightLayout_aspectRatio)?.let { ratio ->
                    if (ratio.contains(":")) {
                        val splits = ratio.split(":")
                        if (splits.count() == 2) {
                            ignoreError {
                                aspectRatio = splits[0].toFloat() / splits[1].toFloat()
                            }
                        }
                    }
                    if (ratio.contains(".")) {
                        aspectRatio = ratio.toFloat()
                    }
                }
                getString(R.styleable.SmartWidthOrHeightLayout_ratioStyle)?.let {
                    aspectRatioStyle = it.toInt()
                }
                this.recycle()
            }
        }
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
//            val widthMode = MeasureSpec.getMode(widthMeasureSpec)
//            val heightMode = MeasureSpec.getMode(heightMeasureSpec)
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        when (aspectRatioStyle) {
            BASE_WIDTH -> {
                val widthSize = MeasureSpec.getSize(widthMeasureSpec)
                setMeasuredDimension(widthSize, (widthSize / aspectRatio).toInt())
            }
            BASE_HEIGHT -> {
                val heightSize = MeasureSpec.getSize(heightMeasureSpec)
                setMeasuredDimension((heightSize * aspectRatio).toInt(), heightSize)
            }
        }
    }
}